package com.mhs.filter;

import com.mhs.exception.BizException;
import com.mhs.utils.BaseContext;
import com.mhs.utils.JwtUtil;
import com.mhs.utils.RedisCache;
import com.mhs.utils.Utils;
import com.mhs.vo.LoginUser;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.Objects;

/**
 * jwt过滤器
 * OncePerRequestFilter: 保证每次请求只会被验证一次
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {//

    @Resource
    private RedisCache redisCache;

    @Override //doFilterInternal
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        //在请求头中尝试获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {//没有token
            //直接放行,交给后面SecurityInterceptor处理
            filterChain.doFilter(request, response);
            return; //这里如果不return,那么SecurityInterceptor响应回来会继续往下执行
        }
        //Token不为空,进行解析

        //解析token
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法或者以过期");
        }

        //从redis中获取用户信息
        String redisKey = "login:" + userId;
//        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        LoginUser loginUser = null;
        try {
            loginUser = redisCache.getCacheObject(redisKey);
        }catch (Exception e){
            e.printStackTrace();
            if (e.getCause() instanceof ClassCastException){
                redisCache.deleteObject("login:"+userId);
            }
        }
        //判断是否为空
        try {
            Utils.checkEmpty(loginUser, "用户未登录");
        } catch (BizException e) {
            throw new RuntimeException(e);
        }
        //存入securityContextHolder
        //获取权限信息,封装到Authentication
        Collection<? extends GrantedAuthority> authorities = loginUser.getAuthorities();
        
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, authorities);
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        //验证通过,把用户id存入当前tomcat线程
        Long id = loginUser.getUser().getId();
        
        try{
            BaseContext.setCurrentId(id);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        
        //放行
        filterChain.doFilter(request,response);    
    }



}
